<?php
namespace app\mp\controller;

use app\admin\controller\MpController;
use app\admin\model\MpReply;
use app\mp\model\MpMessage;
use app\mp\model\MpQrcode;
use app\mp\model\MpQrcodeStatistics;
use EasyWeChat\Foundation\Application;

class Mp extends MpController {
    /**
     * 记录留言
     * @param $message
     * @return bool
     */
    public function defaultMessageHandler($message)
    {
        switch ($message->MsgType) {
            case 'text':
                MpMessage::addText($this->getMp()['id'] ,$message->FromUserName,$message->Content);
                break;
        }
        return false; // 继续执行
    }

    /**
     * 监听是否有场景二维码的消息
     * @param \Symfony\Bridge\PsrHttpMessage\Tests\Fixtures\Message $message
     * @return bool|void
     */
    public function messageListener(&$message)
    {
        if($message->MsgType == 'event') {
            if($qrcode = MpQrcode::get(['ticket'=>$message->Ticket,'mpid'=>$this->getMp()['id']])) {
                if($reply = MpReply::get(['keyword'=>$qrcode['keyword']])) {
                    // 记录日志
                    MpQrcodeStatistics::addStatistics($this->getMp()['id'],$message->FromUserName,$qrcode);

                    $moduleName = $reply['content'];
                    $obj = $this->newMpController($moduleName,$this->getContext(),$this->getApp(),$this->getMp());
                    return $obj->messageHandler($message);
                }
            }

        }
        return false;
    }

    private function newMpController($moduleName,$context = null,$app = null,$mp = null){
        $class = "\\app\\{$moduleName}\\controller\\Mp";
        return new $class($context,$app,$mp);
    }
}